<template>
  <el-form
    @submit.native.prevent="onSubmit"
    label-width="100px"
    label-position="top"
    ref="form"
    :model="form"
    :rules="rules"
  >
    <el-row :gutter="20">
      <el-col :span="10">
        <el-form-item label="患者姓名：" prop="name">
          <el-input v-model.trim="form.name" :disabled="isCheck"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="2" style="height:20px;"></el-col>
      <el-col :span="10">
        <el-form-item label="性别：" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
            <!-- <el-radio :label="0">不详</el-radio> -->
          </el-radio-group>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="10">
        <el-form-item label="出生年月：" prop="birthday">
          <el-date-picker
          :appendToBody="false"
            v-model="form.birthday"
            :picker-options="pickerNow"
            value-format="yyyy-MM-dd"
            type="date"
          ></el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="2" style="height:20px;"></el-col>
      <el-col :span="10">
        <el-form-item label="手机号：" prop="mobile">
          <el-input v-model="form.mobile" :disabled="isCheck"></el-input>
        </el-form-item>
      </el-col>
      <!-- <el-col :span="10">
        <el-form-item label="年龄：" prop="age">
          <el-input v-model.number="form.age" type="number"></el-input>
        </el-form-item>
      </el-col>-->
    </el-row>
    <el-row>
      <el-col :span="10">
        <el-form-item label="身份证号：" prop="idCard">
          <el-input v-model="form.idCard" @blur="onBlurIdCard">
            <el-select
              v-model="form.certificateType"
              style="width:100px;"
              @change="changeSource"
              slot="prepend"
              placeholder="请选择"
            >
              <el-option
                v-for="(item, index) in certificateTypeArray"
                :key="index"
                :label="item.desc"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="2" style="height:20px;"></el-col>
      <el-col :span="10">
        <el-form-item v-if="detail.changePatientSource" label="患者来源：" prop="sourceType">
          <el-select
            v-model="form.sourceType"
            clearable
            style="width:46%;"
            :popper-append-to-body="false"
            placeholder="请选择来源分类"
            value-key="id"
            @change="onChangeTJ"
          >
            <el-option
              v-for="(item, index) in sourceArray"
              :key="index"
              :value="item.id"
              :label="item.desc"
            ></el-option>
          </el-select>
          <!-- <el-select
            style="width:46%;margin-left:2%;"
            v-if="form.sourceType==1"
            filterable
            :filter-method="getDoctorList"
            clearable
            placeholder="请选择医生"
            value-key="id"
            @change="onTCDoctor"
            v-model="tjDoctorObj"
          >
            <el-option
              v-for="(it, index) in doctorArray"
              :key="index"
              :value="it"
              :label="it.trueName"
            ></el-option>
          </el-select>-->
          <doctorSearch v-if="form.sourceType == 1" style="width:40%;margin-left:10px;" ref="tjDoc" v-model="form.sourceCode" :pageSize="20" @change="onTCDoctor"></doctorSearch>
          <el-select
            style="width:46%;margin-left:2%;"
            v-else-if="
              form.sourceType == 2 ||
                form.sourceType == 3||
                form.sourceType == 4
            "
            value-key="id"
            v-model="sourceObj"
            placeholder="请选择"
            @change="onChangeSourceObj"
          >
            <el-option
              v-for="item in sourceObjList"
              :key="item.id"
              :label="item.name"
              :value="item"
            ></el-option>
          </el-select>
          <el-input
            v-else
            style="width:46%;margin-left:2%;"
            placeholder="请输入来源"
            v-model="form.sourceName"
          ></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="10">
        <el-form-item label="婚姻状况：" prop="isMarried">
          <el-radio-group v-model="form.isMarried">
            <el-radio :label="1">已婚</el-radio>
            <el-radio :label="0">未婚</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="2" style="height:20px;"></el-col>
      <el-col :span="10">
        <el-form-item label="民族：" prop="nationId">
          <el-select v-model="form.nationId" clearable>
            <el-option
              v-for="(item, index) in nationArray"
              :key="index"
              :value="item.id"
              :label="item.desc"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="10">
        <el-form-item label="籍贯：" prop="occupationId">
          <!-- <el-select v-model="form.nationalityId" placeholder="请选择">
            <el-option
              v-for="(item,index) in nationalityArray"
              :key="index"
              :value="item.id"
              :label="item.desc"
            ></el-option>
          </el-select>-->
          <v-area :isFull="true" v-model="form.areaArray"></v-area>
        </el-form-item>
      </el-col>
      <el-col :span="2" style="height:20px;"></el-col>
      <el-col :span="10">
        <el-form-item label="职业：" prop="occupationId">
          <el-select v-model="form.occupationId" clearable>
            <el-option
              v-for="(item, index) in occupationArray"
              :key="index"
              :value="item.id"
              :label="item.desc"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="10">
        <el-form-item label="详细地址：">
          <el-input v-model="form.address"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="2" style="height:20px;"></el-col>
      <el-col :span="10">
        <el-form-item label="工作单位：">
          <el-input v-model="form.workUnit"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="10">
        <el-form-item label="就诊卡号：">
          <el-input :disabled="true" v-model="form.archivesCode"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="2" style="height:20px;"></el-col>
      <el-col :span="10">
        <el-form-item label="健康卡号：">
          <el-input :disabled="true" style="width:90%" v-model="form.insuranceCardNumber"></el-input>
          <el-link :underline="false" style="margin-left:10px;" type="primary">冻结健康卡</el-link>
          <!-- <el-input :disabled="true" v-model="form.insuranceCardNumber"></el-input> -->
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="10">
        <el-form-item label="标签：">
          <el-select v-model="form.labelIds" multiple placeholder="请选择">
            <el-option
              v-for="(item, index) in labelArray"
              :key="index"
              :value="item.labelId"
              :label="item.labelName"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="2" style="height:20px;"></el-col>
      <!-- <el-col :span="10">
        <el-form-item label="备注：">
          <el-input type="textarea" v-model="form.remark"></el-input>
        </el-form-item>
      </el-col>-->
    </el-row>
    <!-- <el-row>
    </el-row>-->
    <el-form-item label prop>
      <el-button type="primary" @click="onSubmit">保存</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
import validate from "@/_js/validate.js";
export default {
  props: ["value", "detail"],
  data() {
    return {
      form: {
        hpId: "",
        name: "", //患者姓名
        birthday: "", //出生年月日
        head: "", //头像
        age: "",
        sex: 1,
        certificateType: "",
        mobile: "", //电话
        email: "", //邮箱
        idCard: "", //证件编号
        isMarried: 1, //是否已婚
        nationId: "", //民族
        occupationId: "", //职业id
        nationalityId: "", //国籍
        isMarried: 0,
        workUnit: "", //工作单位
        openId: "",
        provinceId: "",
        province: "",
        city: "",
        district: "",
        cityId: "",
        districtId: "",
        address: "",
        sourceType: "",
        sourceCode: "",
        sourceName: "",
        remark: "",
        tjDoctorId: "",
        medicalCardCode: "",
        labelIds: "", //标签id
        areaArray: []
      },
      jgEnum: [],
      //平台宣传
      ptEnum: [],
      sourceObjList: [],
      tjDoctorObj: null,
      sourceObj: null,
      sourceArray: [], //来源
      nationArray: [], //民族
      occupationArray: [], //职业
      patientArray: [], //患者
      doctorArray: [],
      labelArray: [], //标签
      recommArray: [], //患者来源
      nationalityArray: [],
      certificateTypeArray: [],
      isCheck: false, //是否可以更改姓名、电话
      rules: {
        // idCard: [
        //   { required: true, message: "此项必填", trigger: "blur" },
        //   { validator: validate.vPeopleNumber, trigger: "blur" }
        // ],
        idCard: {
          required: false,
          min: 0,
          max: 18,
          message: "请输入18位以内的证件号",
          trigger: "blur"
        },
        birthday: { required: true, message: "此项必选", trigger: "change" },
        age: [{ required: true, message: "此项必填", trigger: "blur" }],
        mobile: [
          { required: true, message: "此项必填", trigger: "blur" },
          { validator: validate.vPhone, trigger: "blur" }
        ],
        name: { required: true, message: "此项必填", trigger: "blur" },
        sourceType: {
          required: true,
          message: "请选择患者来源类型",
          trigger: "blur"
        }
      },
      pickerNow: {
        disabledDate(time) {
          return time.getTime() > Date.now(); //如果没有后面的-8.64e7就是不可以选择今天的
        }
      }
    };
  },
  components: {
    "v-area": () => import("@/components/area.vue"),
    doctorSearch: () => import("@/pages/_com/newSearchDoctor.vue")
  },
  mounted() {
    this.getInfo();
    this.getBasic();
    this.getDoctorList();
    this.checkPatient();
  },
  methods: {
    onBlurIdCard() {
      const th = this;
      const fn = () => {
        let result = th.$utils.getIdCardInfo(th.form.idCard);
        if (th.form.idCard) {
          th.form.birthday = result.birthday;
          th.form.sex = result.sex == "男" ? 1 : 2;
          th.form.age = th.$utils.getAgeToBirthday(result.birthday);
        }
      };
      validate.vPeopleNumber(null, th.form.idCard, function(err) {
        if (typeof err == "undefined") {
          fn();
        }
      });
    },
    getBasic() {
      this.getCommonConfigByKey("平台宣传").then(res => {
        this.ptEnum = res;
      });
      this.getCommonConfigByKey("推荐来源").then(res => {
        this.sourceArray = res;
      });
      this.getCommonConfigByKey("职业").then(res => {
        this.occupationArray = res;
      });
      this.getCommonConfigByKey("民族").then(res => {
        this.nationArray = res;
      });
      this.getCommonConfigByKey("国籍").then(res => {
        this.nationalityArray = res;
      });
      this.getCommonConfigByKey("证件类型").then(res => {
        this.certificateTypeArray = res;
      });
      this.getCommonConfigByKey("机构推荐").then(res => {
        this.jgEnum = res;
      });
      this.$api
        .selectLabelEmunList({
          hpId: this.adminUser.hpId,
          pageNum: 1,
          pageSize: 1000
        })
        .then(res => {
          if (res.executed) {
            this.labelArray = res.dataBody.list;
          }
        });
      this.getRecommendDetailListByType({ type: "revert" });
    },
    getInfo() {
      let th = this;
      Object.assign(th.form, th.detail);
      let labelIds = th.form.labelIds;
      let label = [];
      for (let i = 0; i < labelIds.length; i++) {
        label.push(parseInt(labelIds[i]));
      }
      let areaArr = [];
      let province = {
        adcode: th.detail.provinceId,
        name: th.detail.province
      };
      if (province) {
        areaArr.push(province);
      }

      let city = {
        name: th.detail.city,
        adcode: th.detail.cityId
      };
      if (city) {
        areaArr.push(city);
      }
      let district = {
        name: th.detail.district,
        adcode: th.detail.districtId
      };
      if (district) {
        areaArr.push(district);
      }
      th.form.areaArray = areaArr;
      th.form.labelIds = label;
    },
    onSubmit() {
      let th = this;
      let j = {};
      let add = function() {
        j.name=j.name.trim();
        th.$api.addPatient(j).then(res => {
          if (res.executed) {
            th.$message.success("保存成功");
            th.$emit("input", false);
            th.$emit("success");
          } else {
            th.$message.error(res.message);
          }
        });
      };
      th.$refs["form"].validate(v => {
        if (v) {
          Object.assign(j, th.form);
          if (j.labelIds) {
            j.labelIds = j.labelIds.join(",");
          }
          if (th.form.areaArray.length == 3) {
            j.provinceId = th.form.areaArray[0].adcode;
            j.cityId = th.form.areaArray[1].adcode;
            j.districtId = th.form.areaArray[2].adcode;
            j.province = th.form.areaArray[0].name;
            j.city = th.form.areaArray[1].name;
            j.district = th.form.areaArray[2].name;
          }
          delete j.areaArray;
          j.hpId = th.adminUser.hpId;
          add();
        }
      });
    },
    changeSource() {
      let th = this;
      th.form.idCard = "";
    },
    // getSource() {
    //   this.form.sourceName = "";
    //   let type = "";
    //   if (this.form.source == "机构推荐") {
    //     type = 2;
    //   } else if (this.form.source == "平台宣传") {
    //     type = 3;
    //   } else if (this.form.source == "活动宣传") {
    //     type = 4;
    //   }
    //   if (type == 2 || type == 3 || type == 4) {
    //     this.$api.findOrganizationAll({ type: type,hpId:this.adminUser.hpId }).then(res => {
    //       if (res.executed) {
    //         this.sourceObjList = res.dataBody.list;
    //       }
    //     });
    //   }
    // },
    //查询医生
    getDoctorList(name) {
      let th = this;
      let j = {
        pageNum: 1,
        pageSize: 20,
        hpId: th.adminUser.hpId,
        doctorName: name
      };
      th.$api.getDoctorPageList(j).then(res => {
        if (res.executed) {
          th.doctorArray = res.dataBody.list;
        }
      });
    },
    //判断有诊疗记录不可修改姓名
    checkPatient() {
      this.$api
        .checkPatientIsExistCureRecord({ patientId: this.detail.patientId })
        .then(res => {
          if (res.executed) this.isCheck = res.data;
        });
    },
    onChangeSourceObj(obj) {
      this.form.sourceName = obj.name;
      this.form.sourceCode = obj.id;
    },
    onChangeTJ() {
      this.form.sourceName = "";
      this.form.sourceCode = "";
      this.form.tjDoctorId = null;
      this.getRecommendDetailListByType({ type: "init" });
    },
    getRecommendDetailListByType({ type }) {
      let params = {
        hpId: this.adminUser.hpId,
        type: ""
      };
      if (
        this.form.sourceType != 1 &&
        this.form.sourceType != 5 &&
        this.form.sourceType != 6
      ) {
        params.type = this.form.sourceType;
      }
      if (params.type) {
        this.$api
          .getRecommendDetailListByType({
            ...params
          })
          .then(res => {
            if (res.executed) {
              this.sourceObjList = res.dataBody;
              this.sourceObj = null;
              if (type && type === "revert") {
                this.sourceObj = this.sourceObjList.filter(
                  obj => obj.id == this.form.sourceCode
                )[0];
              } else {
                this.form.sourceName = "";
                this.form.sourceCode = "";
              }
            }
          });
      }
    },
    //推荐医生
    onTCDoctor(obj) {
      const th = this;
      th.form.tjDoctorId = obj.id;
      th.form.sourceName = obj.trueName;
      th.form.sourceCode = obj.id;
    }
  }
};
</script>
